package com.example.jvm.chapter03;

import java.lang.ref.WeakReference;

public class WeakReferenceExample {
    public static void main(String[] args) {
        // 创建一个对象
        MyObject myObject = new MyObject("Hello, WeakReference!");
        // 创建弱引用，指向该对象
        WeakReference<MyObject> weakReference = new WeakReference<>(myObject);
        // 去除对原对象的强引用
        // myObject = null;
        // 尝试触发垃圾回收
        System.gc();
        // 从弱引用中获取对象
        MyObject retrievedObject = weakReference.get();
        // 如果对象已被回收，retrievedObject 将为 null
        if (retrievedObject == null) {
            System.out.println("Object has been garbage collected.");
        } else {
            System.out.println(retrievedObject.getMessage());
        }
    }

    static class MyObject {
        private String message;

        public MyObject(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }
    }
}